from django.db.models import Sum
from django.db.models.functions import Coalesce
from rest_framework import serializers
from rest_framework.serializers import ModelSerializer

from base.models import CustomSupplier, CustSuppClass, StoreHouse, AccountTitle


class MobileCustSuppClassSerializer(ModelSerializer):
    """
    客商分类
    """
    children = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CustSuppClass
        fields = ["id", "name", "children"]

    def get_children(self, obj):
        if obj.children.count() == 0:
            return None
        return self.__class__(obj.children.all(), many=True).data


class MobileCustomSupplierSerializer(ModelSerializer):
    """
    客户供应商
    """
    cate_name = serializers.CharField(source='cate.name', read_only=True)
    prepay_money = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CustomSupplier
        fields = ["id", "code", "name", "cate", "cate_name", "telephone", "is_vip", "prepay_money", "active_point", "member_point", "consume_point", "help_code"]

    def get_prepay_money(self, obj):
        results = obj.prepayment_set.all().aggregate(amounts=Sum("amount"), deduct_amounts=Sum("deduct_amount"))
        amounts = results.get("amounts") if results.get("amounts") else 0
        deduct_amounts = results.get("deduct_amounts") if results.get("deduct_amounts") else 0
        return amounts - deduct_amounts


class MobileStoreHouseSerializer(ModelSerializer):
    """
    仓库
    """

    class Meta:
        model = StoreHouse
        fields = ["id", "name", "flag"]


class MobileAccountTitleSerializer(ModelSerializer):
    """会计科目"""
    children = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AccountTitle
        fields = ['id', 'name', 'children']

    def get_children(self, obj):
        if obj.children.count() == 0:
            return None
        return self.__class__(obj.children.all(), many=True).data
